package com.liuche.homechat.common.user.service.impl;

import com.liuche.homechat.common.common.annotation.RedissonLock;
import com.liuche.homechat.common.user.enums.ItemTypeEnum;
import com.liuche.homechat.common.common.enums.YNEnum;
import com.liuche.homechat.common.common.exception.BusinessException;
import com.liuche.homechat.common.common.exception.CommonErrorEnum;
import com.liuche.homechat.common.common.service.CusAopProxy;
import com.liuche.homechat.common.user.dao.UserBackpackDao;
import com.liuche.homechat.common.user.domain.entity.UserBackpack;
import com.liuche.homechat.common.user.service.UserBackpackService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author：liuche
 * @Date：2024年06月01日 21:23
 * @Description：
 */
@Service
@Slf4j
public class UserBackpackServiceImpl implements UserBackpackService, CusAopProxy<UserBackpackServiceImpl> {
    private static final Integer WAIT_TIME = 5;

    @Resource
    private UserBackpackDao userBackpackDao;
    @Override
    public void acquireItem(Long uid, ItemTypeEnum itemTypeEnum, Long businessId, Long itemId) {
        String idempotent = getIdempotent(uid, itemTypeEnum.getType(), businessId, itemId);
        self().doAcquireItem(uid, itemId, idempotent);
    }
    @RedissonLock(key="#idempotent")
    public void doAcquireItem(Long uid, Long itemId, String idempotent) {
        log.info("发放物品，幂等号：【{}】", idempotent);
        // 2:判 查找有没有该幂等号的物品
        UserBackpack userBackpack = userBackpackDao.queryUserItemByIdempotent(uid, idempotent);
        if (ObjectUtils.isNotEmpty(userBackpack)) {
            throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
        }

        // 3:更新
        UserBackpack backpack = UserBackpack.builder()
                .idempotent(idempotent)
                .status(YNEnum.N.getStatus())
                .itemId(itemId)
                .uid(uid)
                .build();

        userBackpackDao.save(backpack);
    }

    /**
     * 获取幂等号
     * @param uid 用户id
     * @param itemType 物品类型
     * @param businessType 业务类型
     * @param itemId 物品id
     * @return
     */
    private String getIdempotent(Long uid, Integer itemType, Long businessType, Long itemId) {
        return String.format("%d_%s_%d_%d", uid, itemType, businessType, itemId);
    }
}
